﻿/*
 * signal_handler.cpp
 *
 *  Created on: 2020年11月17日
 *      Author: Dylan.Gao
 */

#include <dm/export.hpp>

#define DM_API_OS_COMMON DM_API_EXPORT

#include <dm/os/signal_handler.hpp>

#include <csignal>

#ifdef WIN32
#include <windows.h>
#endif

namespace dm {
namespace os {

	static sig_atomic_t Signaled = 0;
	static int Signal = -1;

#ifdef WIN32
	static int CtrlType = -1;
#endif

	static void signalHandler(int s) {
		Signaled = 1;
		Signal = s;
	}
#ifdef WIN32
	static bool HandlerRoutine(int ctrlType) {
		Signaled = 1;
		CtrlType = ctrlType;
		return TRUE;
	}
#endif

	CSignalHandler::CSignalHandler() {
		::signal(SIGINT, signalHandler);
		::signal(SIGTERM, signalHandler);

#ifdef WIN32
		SetConsoleCtrlHandler((PHANDLER_ROUTINE)HandlerRoutine, TRUE);
#endif
	}

	CSignalHandler& CSignalHandler::ins() {
		static CSignalHandler i;
		return i;
	}

	bool CSignalHandler::ifSignal()const {
		return Signaled==1;
	}

	int CSignalHandler::signal()const{
		return Signal;
	}

	int CSignalHandler::ctlType()const{
#ifdef WIN32
		return CtrlType;
#else
		return Signal;
#endif
	}

	void CSignalHandler::clearSignals() {
		Signaled = 0;
		Signal = -1;
#ifdef WIN32
		CtrlType = -1;
#endif
	}
}
}
